package com.zmc.order.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.order.infrastructure.bean.query.ReturnInfoQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmc.common.utils.PageUtils;

import com.zmc.order.infrastructure.dao.RefundInfoDao;
import com.zmc.order.infrastructure.entity.RefundInfoEntity;
import com.zmc.order.infrastructure.service.RefundInfoService;


/**
 * @author zmc
 */
@Service("refundInfoService")
public class RefundInfoServiceImpl extends ServiceImpl<RefundInfoDao, RefundInfoEntity> implements RefundInfoService {

    @Autowired
    private AuthTokenService authTokenService;

    @Override
    public PageUtils queryPage(ReturnInfoQuery query) {
        return new PageUtils(baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), getWrapper(query)));
    }

    @Override
    public List<RefundInfoEntity> selectList(ReturnInfoQuery query) {
        return list(getWrapper(query));
    }

    @Override
    public RefundInfoEntity getByOrderSn(String orderSn) {
        LambdaQueryWrapper<RefundInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RefundInfoEntity::getMerchantId, authTokenService.getMemberInfo().getMemberId())
                .eq(RefundInfoEntity::getOrderSn, orderSn)
                .last(" limit 1");
        return getOne(wrapper);
    }

    public LambdaQueryWrapper<RefundInfoEntity> getWrapper(ReturnInfoQuery query) {
        LambdaQueryWrapper<RefundInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RefundInfoEntity::getMerchantId, authTokenService.getMemberInfo().getMemberId())
                .eq(StringUtils.isNotEmpty(query.getOrderSn()), RefundInfoEntity::getOrderSn, query.getOrderSn())
                .eq(!Objects.isNull(query.getStatus()), RefundInfoEntity::getRefundStatus, query.getStatus())
                .orderByDesc(RefundInfoEntity::getCreateTime);
        return wrapper;
    }
}